// setTimeout 性能诊断工具
class SetTimeoutDiagnostic {
  constructor() {
    this.slowTimeouts = new Map()
    this.timeoutCallbacks = new Map()
    this.isMonitoring = false
    this.originalSetTimeout = window.setTimeout
    this.originalSetInterval = window.setInterval
    this.init()
  }

  init() {
    this.interceptSetTimeout()
    this.interceptSetInterval()
    this.startMonitoring()
    console.log('🔍 setTimeout 诊断工具已启动')
  }

  // 拦截 setTimeout
  interceptSetTimeout() {
    const originalSetTimeout = window.setTimeout
    const self = this

    window.setTimeout = function(callback, delay, ...args) {
      const timeoutId = originalSetTimeout.call(this, function() {
        const startTime = performance.now()
        
        try {
          // 执行原始回调
          callback.apply(this, args)
        } catch (error) {
          console.error('setTimeout 回调执行错误:', error)
        } finally {
          const endTime = performance.now()
          const duration = endTime - startTime
          
          // 记录执行时间
          self.recordTimeoutExecution(timeoutId, duration, callback, delay)
        }
      }, delay, ...args)

      // 记录回调信息
      self.timeoutCallbacks.set(timeoutId, {
        callback: callback.toString().substring(0, 200),
        delay: delay,
        timestamp: Date.now(),
        stack: new Error().stack
      })

      return timeoutId
    }
  }

  // 拦截 setInterval
  interceptSetInterval() {
    const originalSetInterval = window.setInterval
    const self = this

    window.setInterval = function(callback, delay, ...args) {
      const intervalId = originalSetInterval.call(this, function() {
        const startTime = performance.now()
        
        try {
          callback.apply(this, args)
        } catch (error) {
          console.error('setInterval 回调执行错误:', error)
        } finally {
          const endTime = performance.now()
          const duration = endTime - startTime
          
          self.recordTimeoutExecution(intervalId, duration, callback, delay)
        }
      }, delay, ...args)

      self.timeoutCallbacks.set(intervalId, {
        callback: callback.toString().substring(0, 200),
        delay: delay,
        timestamp: Date.now(),
        stack: new Error().stack,
        isInterval: true
      })

      return intervalId
    }
  }

  // 记录执行时间
  recordTimeoutExecution(id, duration, callback, delay) {
    if (duration > 50) { // 超过50ms认为是慢函数
      const callbackInfo = this.timeoutCallbacks.get(id)
      
      const slowTimeout = {
        id: id,
        duration: duration,
        delay: delay,
        callback: callback.toString().substring(0, 200),
        timestamp: Date.now(),
        count: (this.slowTimeouts.get(id)?.count || 0) + 1,
        stack: callbackInfo?.stack,
        isInterval: callbackInfo?.isInterval || false
      }

      this.slowTimeouts.set(id, slowTimeout)
      
      // 输出警告
      this.logSlowTimeout(slowTimeout)
      
      // 分析可能的原因
      this.analyzeSlowTimeout(slowTimeout)
    }
  }

  // 记录慢函数
  logSlowTimeout(timeout) {
    const type = timeout.isInterval ? 'setInterval' : 'setTimeout'
    console.warn(`🐌 慢函数检测: ${type} 执行了 ${Math.round(timeout.duration)}ms`)
    console.warn(`   延迟: ${timeout.delay}ms`)
    console.warn(`   回调: ${timeout.callback}`)
    
    if (timeout.count > 1) {
      console.warn(`   重复次数: ${timeout.count}`)
    }
  }

  // 分析慢函数原因
  analyzeSlowTimeout(timeout) {
    const callback = timeout.callback.toLowerCase()
    
    console.group('🔍 原因分析:')
    
    // 检查是否是外部脚本
    if (callback.includes('detect') || callback.includes('translate') || callback.includes('lang')) {
      console.warn('⚠️ 可能是浏览器扩展（翻译、语言检测）导致的')
      console.warn('💡 建议: 禁用相关浏览器扩展')
    }
    
    // 检查是否是网络请求
    if (callback.includes('fetch') || callback.includes('xmlhttprequest') || callback.includes('ajax')) {
      console.warn('⚠️ 可能是网络请求超时')
      console.warn('💡 建议: 检查网络连接，优化API响应时间')
    }
    
    // 检查是否是DOM操作
    if (callback.includes('queryselector') || callback.includes('getelementbyid') || callback.includes('innerhtml')) {
      console.warn('⚠️ 可能是DOM操作过多')
      console.warn('💡 建议: 优化DOM查询，使用缓存')
    }
    
    // 检查是否是计算密集型操作
    if (callback.includes('for') || callback.includes('while') || callback.includes('math.')) {
      console.warn('⚠️ 可能是计算密集型操作')
      console.warn('💡 建议: 使用 Web Workers 或优化算法')
    }
    
    // 检查是否是第三方库
    if (callback.includes('jquery') || callback.includes('lodash') || callback.includes('moment')) {
      console.warn('⚠️ 可能是第三方库性能问题')
      console.warn('💡 建议: 更新库版本或寻找替代方案')
    }
    
    console.groupEnd()
  }

  // 开始监控
  startMonitoring() {
    this.isMonitoring = true
    
    // 定期清理旧的记录 - 使用原始setInterval避免递归
    if (this.originalSetInterval) {
      this.originalSetInterval(() => {
        this.cleanupOldRecords()
      }, 30000) // 每30秒清理一次
    }
  }

  // 清理旧记录
  cleanupOldRecords() {
    const now = Date.now()
    const maxAge = 5 * 60 * 1000 // 5分钟
    
    for (const [id, timeout] of this.slowTimeouts) {
      if (now - timeout.timestamp > maxAge) {
        this.slowTimeouts.delete(id)
        this.timeoutCallbacks.delete(id)
      }
    }
  }

  // 获取慢函数报告
  getSlowTimeoutsReport() {
    const report = {
      timestamp: new Date().toISOString(),
      totalSlowTimeouts: this.slowTimeouts.size,
      slowTimeouts: Array.from(this.slowTimeouts.values()).sort((a, b) => b.duration - a.duration),
      summary: this.generateSummary()
    }
    
    return report
  }

  // 生成摘要
  generateSummary() {
    const timeouts = Array.from(this.slowTimeouts.values())
    
    if (timeouts.length === 0) {
      return {
        status: 'good',
        message: '没有检测到慢的 setTimeout/setInterval'
      }
    }
    
    const avgDuration = timeouts.reduce((sum, t) => sum + t.duration, 0) / timeouts.length
    const maxDuration = Math.max(...timeouts.map(t => t.duration))
    
    let status = 'good'
    let message = ''
    
    if (maxDuration > 1000) {
      status = 'critical'
      message = `检测到严重性能问题，最慢的函数执行了 ${Math.round(maxDuration)}ms`
    } else if (maxDuration > 500) {
      status = 'warning'
      message = `检测到性能问题，最慢的函数执行了 ${Math.round(maxDuration)}ms`
    } else {
      status = 'info'
      message = `检测到轻微性能问题，平均执行时间 ${Math.round(avgDuration)}ms`
    }
    
    return {
      status,
      message,
      avgDuration: Math.round(avgDuration),
      maxDuration: Math.round(maxDuration),
      totalCount: timeouts.length
    }
  }

  // 导出报告
  exportReport() {
    const report = this.getSlowTimeoutsReport()
    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `settimeout-report-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
    
    console.log('📊 setTimeout 性能报告已导出')
  }

  // 清除记录
  clearRecords() {
    this.slowTimeouts.clear()
    this.timeoutCallbacks.clear()
    console.log('🗑️ setTimeout 记录已清除')
  }

  // 停止监控
  stopMonitoring() {
    this.isMonitoring = false
    console.log('⏹️ setTimeout 监控已停止')
  }
}

// 创建全局实例
window.setTimeoutDiagnostic = new SetTimeoutDiagnostic()

// 提供全局访问方法
window.getSetTimeoutReport = () => window.setTimeoutDiagnostic.getSlowTimeoutsReport()
window.exportSetTimeoutReport = () => window.setTimeoutDiagnostic.exportReport()
window.clearSetTimeoutRecords = () => window.setTimeoutDiagnostic.clearRecords()

console.log('🔧 setTimeout 诊断工具已加载')
console.log('💡 使用 getSetTimeoutReport() 查看报告')
console.log('💡 使用 exportSetTimeoutReport() 导出报告')
console.log('💡 使用 clearSetTimeoutRecords() 清除记录')
